package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.base.AdvInfo;
import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.tabview.difficultpoint.AttendanceActivity;
import com.tabview.difficultpoint.CourseDifficultPointsActivity;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.ui.task.AdvertisementTask;
import com.xudow.app.ui.task.StudentListTask;
import com.xudow.app.ui.widget.gallery.XViewPaper;
import com.xudow.app.ui.widget.tab.ViewPagerIndicatorView;
import com.xudow.app.util.AdvertisementUtils;
import com.xudow.app.util.ImageUtils;
import com.xudow.app.util.Maps;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 我的学习Activity
 *
 * @author lukecheng
 */
public class StudyActivity extends BaseActivity
        implements ViewPagerIndicatorView.PageChangeListener {

    /**
     * 广告图片
     */
    private XViewPaper xViewPaper;
    private LinearLayout ovalLayout;
    private List<View> listViews;
    private List<AdvInfo> advs;
    private RelativeLayout advLayout;

    private ViewPagerIndicatorView viewPagerIndicatorView;
    private LinearLayout singleStudentView;

    private StudentListTask studentListTask;
    private AdvertisementTask advertisementTask;

    /**
     * 学生信息
     */
    private UserProfileWithOther[] students;

    /**
     * 当前选择的学生
     */
    private UserProfileWithOther currentStudent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_study);

        xViewPaper = (XViewPaper) findViewById(R.id.gallery);
        ovalLayout = (LinearLayout) findViewById(R.id.vb);
        advLayout = (RelativeLayout) findViewById(R.id.ad);

        viewPagerIndicatorView = (ViewPagerIndicatorView) findViewById(R.id.viewpager_indicator_view);
        singleStudentView = (LinearLayout) findViewById(R.id.single_student_view);

        showLodingDialog(getString(R.string.loading));

        studentListTask = new StudentListTask(this, studentListHandler);
        addTask(studentListTask);
        studentListTask.execute();

        //加载广告
        HashMap<String, String> advParam = Maps.newHashMap();
        advParam.put("app_page", "2");

        advertisementTask = new AdvertisementTask(this, advertisementTaskHandler);
        addTask(advertisementTask);
        advertisementTask.execute(advParam);
    }

    public void onBackBtnClick(View view) {
        finish();
    }

    @Override
    public boolean isNeedLogin() {
        return true;
    }

    /**
     * 设置广告图片
     */
    private void initViewPager() {
        listViews = new ArrayList<View>();

        for (int i = 0; i < advs.size(); i++) {
            final AdvInfo advInfo = advs.get(i);

            ImageView imageView = new ImageView(this);
            imageView.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    AdvertisementUtils.open(StudyActivity.this, advInfo);
                }
            });

            String imageUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, advInfo.getImgPath());
            ImageUtils.loadImage(this, imageView, imageUrl, R.mipmap.def_portrait);

            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            listViews.add(imageView);
        }

        xViewPaper.start(this, listViews, 4000, ovalLayout,
                R.layout.ad_bottom_item, R.id.ad_item_v,
                R.drawable.dot_focused, R.drawable.dot_normal);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (studentListTask != null && !studentListTask.isCancelled()) {
                studentListTask.cancel(true);
                studentListTask = null;
                finish();
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    public void onFunctionItemClick(View view) {
        Intent intent = null;

        switch (view.getId()) {
            case R.id.class_schedule_item:
                intent = new Intent(this, ClazzScheduleActivity.class); // 课程表
                break;
            case R.id.class_log_item:
                intent = new Intent(this, ClazzLogActivity.class); // 考勤

                break;
            case R.id.class_course_item:
//                intent = new Intent(this, ClazzCourseActivity.class); // 课程中心
                intent = new Intent(this, AttendanceActivity.class);
                break;
            case R.id.class_mistake_item:
                intent = new Intent(this, ClazzMistakeActivity.class); // 错题本
                break;

            case R.id.class_course_difficult_points_item: // 困难点
                intent = new Intent(this, CourseDifficultPointsActivity.class);
                break;
        }

        if (null != currentStudent) {
            intent.putExtra("studentId", "" + currentStudent.getId());
        }

        startActivity(intent);
    }

    private Handler studentListHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (StudentListTask.SUCCESS == msg.what) {
                onStudentListSuccess(msg.getData());
            } else {
                singleStudentView.setVisibility(View.GONE);

                String message = getString(R.string.loading_fail);
                Toast.makeText(StudyActivity.this, message, Toast.LENGTH_LONG).show();
            }
        }
    };

    private void onStudentListSuccess(Bundle data) {
        students = (UserProfileWithOther[]) data.get("students");

        if (null == students) {
            List<String> titles = new ArrayList<String>();
            List<View> views = new ArrayList<View>();

            titles.add("");
            views.add(LayoutInflater.from(this).inflate(R.layout.layout_study, null));


            List<String> titles1 = new ArrayList<String>();
            List<View> views1 = new ArrayList<View>();
            for (int i = 0; i < 10; i++) {
                titles1.add("title" + i);
                views1.add(LayoutInflater.from(this).inflate(R.layout.layout_study, null));
            }

            viewPagerIndicatorView.setVisibility(View.GONE);
            singleStudentView.setVisibility(View.VISIBLE);
        } else {
            if (students.length > 1) {
                List<String> titles = new ArrayList<String>();
                List<View> views = new ArrayList<View>();

                for (UserProfileWithOther student : students) {
                    titles.add(student.getName());
                    views.add(LayoutInflater.from(this).inflate(R.layout.layout_study, null));
                }

                viewPagerIndicatorView.setupLayout(titles, views);
                singleStudentView.setVisibility(View.GONE);
                viewPagerIndicatorView.setVisibility(View.VISIBLE);

                viewPagerIndicatorView.setPageChangeListener(this);
            } else if (students.length == 1) {
                viewPagerIndicatorView.setVisibility(View.GONE);
                singleStudentView.setVisibility(View.VISIBLE);
            }

            if (students.length > 0) {
                currentStudent = students[0];
            }
        }
    }

    @Override
    public void onChange(String tag) {
        for (UserProfileWithOther st : students) {
            if (st.getName().equals(tag)) {
                currentStudent = st;
            }
        }
    }

    /**
     * 广告加载Handler
     */
    private Handler advertisementTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (AdvertisementTask.SUCCESS == msg.what) {
                AdvInfo[] dataArr = (AdvInfo[]) msg.getData().getSerializable("advs");

                if (null == dataArr || dataArr.length <= 0) {
                    return;
                }

                advs = new ArrayList<AdvInfo>();
                advs.addAll(Arrays.asList(dataArr));

                initViewPager();

                advLayout.setVisibility(View.VISIBLE);
            }
        }
    };

}
